package corejava.corejava1.ch09;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * @version 1.33 2007-06-12
 * @author Cay Horstmann
 */
public class Ch9_04_RadioButtonTest {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                RadioButtonFrame frame = new RadioButtonFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

/**
 * A frame with a sample text label and radio buttons for selecting font sizes.
 */
@SuppressWarnings("serial")
class RadioButtonFrame extends JFrame {
    public RadioButtonFrame() {
        setTitle("RadioButtonTest");
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

        // add the sample text label
        label = new JLabel("The quick brown fox jumps over the lazy dog.");
        label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
        add(label, BorderLayout.CENTER);

        // add the radio buttons
        buttonPanel = new JPanel();
        group = new ButtonGroup();  // 按钮组,实现在一组按钮中只能选择一项
        // 按钮组仅仅控制按钮的行为,如果想把这些按钮组织在一起,需要把它们加到容器中

        addRadioButton("Small", 8);
        addRadioButton("Medium", 12);
        addRadioButton("Large", 18);
        addRadioButton("Extra large", 36);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    /**
     * Adds a radio button that sets the font size of the sample text.
     * 
     * @param name
     *            the string to appear on the button
     * @param size
     *            the font size that this button sets
     */
    public void addRadioButton(String name, final int size) {
        boolean selected = size == DEFAULT_SIZE;
        JRadioButton button = new JRadioButton(name, selected);
        group.add(button);
        buttonPanel.add(button);

        // this listener sets the label font size
        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                // size refers to the final parameter of the addRadioButton
                // method
                label.setFont(new Font("Serif", Font.PLAIN, size));
            }
        };
        button.addActionListener(listener);
    }

    public static final int  DEFAULT_WIDTH  = 400;
    public static final int  DEFAULT_HEIGHT = 200;
    private JPanel           buttonPanel;
    private ButtonGroup      group;
    private JLabel           label;
    private static final int DEFAULT_SIZE   = 12;
}

// ButtonGroup有一个getSelection方法,返回附加在选中的那个按钮上的ButtonModel的引用.
// 只有通过setActionCommomand命令明确地为所有单选按钮设定动作命令后
// 才能通过调用方法buttonGroupgetSelection().getActionCommand()获得当前选择的按钮的动作命令
